package com.nabton.ndscollector.connection;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

import com.nabton.ndscollector.values.NabControl;
import com.nabton.ndscollector.values.NabEntry;
import com.nabton.ndscollector.values.NabStatus;
import com.nabton.ndscollector.connection.RequestInterface;

public class ClientHandler extends AbstractHandler
{
    public RequestInterface interfaceNDS;
    public ClientHandler(RequestInterface link)
    {
        interfaceNDS = link;
    }
    
    public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) 
            throws IOException, ServletException
    {
        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        baseRequest.setHandled(true);
        if (request.getParameter("sid") != null)
        {
            int streamId   = Integer.parseInt(request.getParameter("sid"));
            double data   = Double.parseDouble(request.getParameter("data"));
            
            NabEntry entry = new NabEntry();
            entry.setStreamId(streamId);
            entry.setData(data);

            NabStatus s = interfaceNDS.verifyStreamId(streamId);
            
            if (NabStatus.OK == s)
            {
                s = interfaceNDS.handleDataRequest(entry);
                
                List<NabControl> controlMessages;
                controlMessages = interfaceNDS.fetchControlMessage(streamId);
                String controlString = "";
                for (NabControl element : controlMessages) 
                {
                    controlString += element.getTag() + " " + element.getValue() + "\n";
                }
                //Respond to client
                response.getWriter().println(controlString);
            }   
            
        }
        
    }
}

